package com.wzq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzq.dao.pojo.Code;
import com.wzq.dao.pojo.Like;
import com.wzq.dao.pojo.Result;
import com.wzq.service.ILikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yzc
 * @since 2022-08-31
 */
@RestController
@RequestMapping("/like")
public class LikeController {

    @Autowired
    private ILikeService iLikeService;
    //   添加
    @PostMapping
    public Result save(@RequestBody Like like) {
        boolean flag = iLikeService.save(like);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }

    //查询是否点赞
    @PostMapping("islike")
    public Result islike(@RequestBody Like like) {
        LambdaQueryWrapper<Like> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Like::getP_id,like.getP_id());
        lambdaQueryWrapper.eq(Like::getW_id,like.getW_id());
        lambdaQueryWrapper.last("limit 1");
        Like islike = iLikeService.getOne(lambdaQueryWrapper);
        if (islike == null){
            return new Result(Code.SAVE_OK,"已点赞");
        }else{
            return new Result(Code.SAVE_ERR,"未点赞");
        }
    }

    //   修改
    @PutMapping
    public Result update(@RequestBody Like like) {
        boolean flag = iLikeService.updateById(like);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }

    //    删除点赞
    @DeleteMapping("/deleteLike")
    public Result deleteById(@RequestBody Like like) {
        LambdaQueryWrapper<Like> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Like::getP_id,like.getP_id());
        lambdaQueryWrapper.eq(Like::getW_id,like.getW_id());
        lambdaQueryWrapper.last("limit 1");
        boolean remove = iLikeService.remove(lambdaQueryWrapper);
        return new Result(remove ? Code.DELETE_OK:Code.DELETE_ERR,remove);
    }

    //    获得id对应用户信息
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Like like = iLikeService.getById(id);
        Integer code = like != null ? Code.GET_OK : Code.GET_ERR;
        String msg = like != null ? "" : "数据查询失败，请重试！";
        return new Result(code,like,msg);
    }

    //     获得所有用户信息
    @GetMapping
    public Result getAll() {
        List<Like> list = iLikeService.list();
        System.out.println(list);
        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
        String msg = list != null ? "" : "数据查询失败，请重试！";
        return new Result(code,list,msg);
    }

}
